#!/usr/bin/python

def dec_to_36(dec):
  key = '0123456789abcdefghijklmnopqrstuvwxyz'
  result = ''
  while 1:
    div = dec / 36
    mod = dec % 36
    dec = div
    result = key[mod] + result
    if dec == 0:
      break
  return result


import os, re, sys

repo_path = sys.argv[1]
rev_path = os.path.join(repo_path, 'db', 'revs')
current_path = os.path.join(repo_path, 'db', 'current')

id_re = re.compile(r'^id:\ ([a-z0-9]+)\.([a-z0-9]+)\.r([0-9]+).*')

max_node_id = 0
max_copy_id = 0
max_rev_id = 0

for rev in os.listdir(rev_path):
  f = open(os.path.join(rev_path, rev), 'r')
  
  for line in f:
    m = id_re.match(line)
    if m:
      node_id = int(m.group(1), 36)
      copy_id = int(m.group(2), 36)
      rev_id = int(m.group(3), 10)

      if copy_id > max_copy_id:
        max_copy_id = copy_id
        
      if node_id > max_node_id:
        max_node_id = node_id

      if rev_id > max_rev_id:
        max_rev_id = rev_id

f = open(current_path, 'w+b')
f.write("%d %s %s\n" % (max_rev_id, dec_to_36(max_node_id+1),
                        dec_to_36(max_copy_id+1)))
f.close()


